﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Ext.Net;
using Sio.Mdm.Client;
using Sio.Mdm.Types;
using IDM.BF.AdministrationService;
using Sio.Mdm.Entities;
using Microsoft.Win32;

namespace IDM.Web
{
    public partial class Login : Sio.Mdm.Web.Controls.Page
    {
        private bool HasFirebird
        {
            get
            {
                return true;
                /*
                return Registry.GetValue(
                    "HKEY_LOCAL_MACHINE\\Software\\Firebird Project\\Firebird Server\\Instances\\",
                    "DefaultInstance",
                    null
                ) != null; */
            }
        }

        private bool HasDatabase
        {
            get
            {
                IAuthorizationService service = ServiceFactory.GetService<IAuthorizationService>();
                return service.HasDatabase() == null;
            }
        }

        private bool ShouldInstall
        {
            get
            {
                return !HasDatabase || !HasFirebird;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            if (ShouldInstall)
            {
                Response.Redirect("Help.aspx");
                Response.End();
            }

            base.OnLoad(e);
        }

        protected void Login_Click(object sender, DirectEventArgs e)
        {   
            IAuthorizationService auth = ServiceFactory.GetService<IAuthorizationService>();
            Session session;
            Result error;

            error = auth.Login(UserName.Text, Password.Text, out session);
            
            if (error == null)
            {   
                FormsAuthentication.SetAuthCookie(UserName.Text, false);                
                Response.Redirect("Default.aspx");
            }
            else 
            {
                e.Success = false;
                e.ErrorMessage = error.ToString();
            }
        }
    }
}
